package com.xulu.romance.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xulu.romance.constants.Constant;
import com.xulu.romance.pojo.Files;
import com.xulu.romance.pojo.UserLog;
import com.xulu.romance.service.FileService;
import com.xulu.romance.utils.R;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin
@RequestMapping("/api/file")
@Api(tags = "上传下载")
@Slf4j
public class FileController {

    @Value("${file.upload.path}")
    private String path;

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    private R upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        String uuid = IdUtil.fastSimpleUUID();

        File uploadFile=new File(path+uuid+StrUtil.DOT+type);
        File parentFile = uploadFile.getParentFile();
        if (!parentFile.exists()){
            parentFile.mkdirs();
        }
        String url;
        String md5;
        file.transferTo(uploadFile);
        md5=SecureUtil.md5(uploadFile);
        Files files = getFiles(md5);
        if (files!=null){
            url= files.getUrl();
            uploadFile.delete();
        }else {
            url="http://localhost:8080/api/file/download/"+uuid+StrUtil.DOT+type;
        }



        Files saveFile=new Files();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setSize(size/1024);
        saveFile.setUrl(url);
        saveFile.setMd5(md5);
        fileService.save(saveFile);

        return Objects.requireNonNull(new R().put("msg", url)).put("code", Constant.SUCCESS_CODE);
    }

    private Files getFiles(String md5) {
        QueryWrapper<Files> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<Files> list = fileService.list(queryWrapper);
        return list.isEmpty() ?null:list.get(0);
    }

    @GetMapping("/download/{fileId}")
    @ApiOperation("下载文件")
    public void download(@PathVariable String fileId, HttpServletResponse response) throws IOException {
        File files=new File(path+fileId);
        ServletOutputStream outputStream = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileId,"UTF-8"));
        response.setContentType("application/octet-stream");

        outputStream.write(FileUtil.readBytes(files));
        outputStream.flush();
        outputStream.close();
    }

    @GetMapping("/findAll/{currentPage}/{size}")
    @ApiOperation("分页查询")
    public R findPage(@PathVariable Long currentPage, @PathVariable Long size, Files condition) {
        // 创建分页对象
        IPage<Files> page = new Page<>(currentPage, size);

        // 构建查询条件
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        if (condition != null) {
            // 如果条件不为空，添加相应的查询条件
            if (StringUtils.isNotBlank(condition.getName())) {
                queryWrapper.like("name", condition.getName());
            }
        }

        // 执行分页查询
        IPage<Files> filesIPage = fileService.page(page, queryWrapper);

        // 获取查询结果
        List<Files> filesList = filesIPage.getRecords();
        long total = filesIPage.getTotal();


        // 返回结果
        return Objects.requireNonNull(R.ok().put("filesList", filesList)).put("count", total);
    }

    @GetMapping("/getFileCount")
    @ApiOperation("文件数量")
    public R getFileCount(){
        long count = fileService.count();
        return new R().put("count",count);
    }

}
